package util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
	 @SuppressWarnings("unchecked")
	public static Object toJsonObject(String jsonString, @SuppressWarnings("rawtypes") Class clazz){
	        ObjectMapper mapper = new ObjectMapper();
	        Object obj = null;
	        try {
	            obj = mapper.readValue(jsonString, clazz);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return obj;
	    }

	    public static String toJsonString(Object object){
	        ObjectMapper mapper = new ObjectMapper();
	        String result = null;
	        try {
	            result = mapper.writeValueAsString(object);
	        } catch (JsonProcessingException e) {
	            e.printStackTrace();
	        }
	        return result;
	    }
	    
	    public static Object toJsonListObject(String jsonString,Class<?> collectionClass, Class<?>... elementClasses){
	    	 ObjectMapper mapper = new ObjectMapper();
		     Object obj = null;
		     try {
				obj = mapper.readValue(jsonString, getCollectionType(mapper, collectionClass, elementClasses));
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		     return obj;
	    }
	    
	    
	    
	    public static JavaType getCollectionType(ObjectMapper mapper,Class<?> collectionClass, Class<?>... elementClasses) {     
	        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);     
	    }  
	    
	    public static String getJsonStringfromStream(InputStream in){
	    	BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	    	StringBuilder builder = new StringBuilder();
	    	 String temp;  
	            try {
					while ((temp = reader.readLine()) != null) {  
					    builder.append(temp);  
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally{
					  try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
	          
	            return builder.toString();
	            
	    }
	    
	    
	      
}
